package com.example.contextcube;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.contextcube.adapter.WordAdapter;
import com.example.contextcube.db.DictionaryDatabaseHelper;
import com.example.contextcube.model.Word;
import com.example.contextcube.util.FavoriteManager;
import com.example.contextcube.util.ToastManager;
import com.example.contextcube.view.AlphabetIndexView;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FavoritesFragment extends Fragment {
    private static final String TAG = "FavoritesFragment";

    private RecyclerView favoritesRecycler;
    private LinearLayout emptyStateLayout;
    private ChipGroup sortChipGroup;
    private Chip chipSortTime;
    private Chip chipSortAlphabet;
    private AlphabetIndexView alphabetIndexView;
    private TextView letterHintText;
    
    private WordAdapter adapter;
    private DictionaryDatabaseHelper dbHelper;
    private Handler mainHandler;
    private FavoriteManager favoriteManager;
    
    // 保存字母索引对应的位置
    private Map<String, Integer> letterPositionMap = new HashMap<>();
    // 是否显示字母索引
    private boolean isAlphabetIndexVisible = false;
    // 字母提示显示和隐藏的Handler
    private Handler letterHintHandler = new Handler(Looper.getMainLooper());
    private Runnable hideLetterHintRunnable;
    
    private boolean sortByAlphabet = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorites, container, false);
        
        // 初始化视图
        favoritesRecycler = view.findViewById(R.id.favorites_recycler);
        emptyStateLayout = view.findViewById(R.id.empty_state_layout);
        sortChipGroup = view.findViewById(R.id.sort_chip_group);
        chipSortTime = view.findViewById(R.id.chip_sort_time);
        chipSortAlphabet = view.findViewById(R.id.chip_sort_alphabet);
        alphabetIndexView = view.findViewById(R.id.alphabet_index_view);
        letterHintText = view.findViewById(R.id.letter_hint_text);
        
        // 初始化数据库和Handler
        dbHelper = new DictionaryDatabaseHelper(requireContext());
        mainHandler = new Handler(Looper.getMainLooper());
        
        // 初始化FavoriteManager
        favoriteManager = FavoriteManager.getInstance();
        favoriteManager.setDatabaseHelper(dbHelper);
        
        // 设置适配器
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        favoritesRecycler.setLayoutManager(layoutManager);
        adapter = new WordAdapter(this::onWordItemClick, this::onFavoriteClick, dbHelper);
        favoritesRecycler.setAdapter(adapter);
        
        // 设置排序切换监听
        setupSortingChips();
        
        // 设置字母索引触摸监听
        setupAlphabetIndexView();
        
        // 初始化字母提示隐藏Runnable
        hideLetterHintRunnable = () -> letterHintText.setVisibility(View.GONE);
        
        // 加载收藏的单词
        loadFavoriteWords();
        
        return view;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时重新加载收藏单词
        loadFavoriteWords();
    }
    
    /**
     * 设置排序选项监听
     */
    private void setupSortingChips() {
        // 设置芯片组选择监听
        sortChipGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.chip_sort_alphabet) {
                sortByAlphabet = true;
                showAlphabetIndexView(true);
            } else if (checkedId == R.id.chip_sort_time) {
                sortByAlphabet = false;
                showAlphabetIndexView(false);
            } else {
                // 如果没有选中项，则强制选中上一个选中的项
                if (sortByAlphabet) {
                    chipSortAlphabet.setChecked(true);
                } else {
                    chipSortTime.setChecked(true);
                }
                return; // 不重新加载数据
            }
            
            // 重新加载收藏的单词
            loadFavoriteWords();
        });
        
        // 给每个Chip添加点击监听，防止取消选中
        chipSortTime.setOnClickListener(v -> {
            // 如果当前未选中，则选中它
            if (!chipSortTime.isChecked()) {
                chipSortTime.setChecked(true);
            }
        });
        
        chipSortAlphabet.setOnClickListener(v -> {
            // 如果当前未选中，则选中它
            if (!chipSortAlphabet.isChecked()) {
                chipSortAlphabet.setChecked(true);
            }
        });
    }
    
    /**
     * 设置字母索引视图
     */
    private void setupAlphabetIndexView() {
        alphabetIndexView.setOnIndexTouchListener((letter, position) -> {
            // 显示字母提示
            showLetterHint(letter);
            
            // 滚动到对应的位置
            scrollToLetter(letter);
        });
    }
    
    /**
     * 显示字母提示
     */
    private void showLetterHint(String letter) {
        letterHintText.setText(letter);
        letterHintText.setVisibility(View.VISIBLE);
        
        // 移除之前的延迟隐藏任务
        letterHintHandler.removeCallbacks(hideLetterHintRunnable);
        // 延迟1秒后隐藏提示
        letterHintHandler.postDelayed(hideLetterHintRunnable, 1000);
    }
    
    /**
     * 滚动到对应字母的位置
     */
    private void scrollToLetter(String letter) {
        // 在字母位置映射中查找
        if (letterPositionMap.containsKey(letter)) {
            int position = letterPositionMap.get(letter);
            ((LinearLayoutManager) favoritesRecycler.getLayoutManager()).scrollToPositionWithOffset(position, 0);
        } else {
            // 如果找不到精确匹配，则找到最接近的字母
            scrollToClosestLetter(letter);
        }
    }
    
    /**
     * 滚动到最接近的字母位置
     */
    private void scrollToClosestLetter(String targetLetter) {
        // 尝试查找较小的字母
        char targetChar = targetLetter.charAt(0);
        String closestLetter = null;
        
        // 遍历所有字母，找出小于目标字母的最大字母
        for (String letter : letterPositionMap.keySet()) {
            char currentChar = letter.charAt(0);
            if (currentChar <= targetChar && (closestLetter == null || currentChar > closestLetter.charAt(0))) {
                closestLetter = letter;
            }
        }
        
        // 如果找到了接近的字母，滚动到该位置
        if (closestLetter != null) {
            int position = letterPositionMap.get(closestLetter);
            ((LinearLayoutManager) favoritesRecycler.getLayoutManager()).scrollToPositionWithOffset(position, 0);
        } else {
            // 如果没有找到较小的字母，滚动到列表顶部
            favoritesRecycler.scrollToPosition(0);
        }
    }
    
    /**
     * 显示或隐藏字母索引视图
     */
    private void showAlphabetIndexView(boolean show) {
        isAlphabetIndexVisible = show;
        alphabetIndexView.setVisibility(show ? View.VISIBLE : View.GONE);
        
        // 调整RecyclerView的padding，为字母索引腾出空间
        if (show) {
            favoritesRecycler.setPadding(
                    favoritesRecycler.getPaddingLeft(),
                    favoritesRecycler.getPaddingTop(),
                    getResources().getDimensionPixelSize(R.dimen.spacing_normal) + 24, // 增加右侧padding
                    favoritesRecycler.getPaddingBottom()
            );
        } else {
            favoritesRecycler.setPadding(
                    favoritesRecycler.getPaddingLeft(),
                    favoritesRecycler.getPaddingTop(),
                    getResources().getDimensionPixelSize(R.dimen.spacing_normal), // 恢复原有padding
                    favoritesRecycler.getPaddingBottom()
            );
        }
    }
    
    /**
     * 加载收藏的单词
     */
    private void loadFavoriteWords() {
        Log.d(TAG, "loadFavoriteWords: 开始加载收藏单词，排序方式: " + (sortByAlphabet ? "字母" : "时间"));
        
        // 使用后台线程加载数据
        new Thread(() -> {
            try {
                final List<Word> favoriteWords = dbHelper.getFavoriteWords(sortByAlphabet);
                
                // 如果是按字母排序，创建字母位置映射
                if (sortByAlphabet) {
                    createLetterPositionMap(favoriteWords);
                } else {
                    letterPositionMap.clear();
                }
                
                // 在主线程更新UI
                mainHandler.post(() -> {
                    adapter.setWords(favoriteWords);
                    
                    // 显示或隐藏空状态
                    showEmptyState(favoriteWords.isEmpty());
                    
                    // 更新字母索引视图显示状态
                    showAlphabetIndexView(sortByAlphabet && !favoriteWords.isEmpty());
                });
            } catch (Exception e) {
                Log.e(TAG, "loadFavoriteWords: 加载收藏单词出错", e);
                
                // 在主线程显示错误
                mainHandler.post(() -> {
                    ToastManager.showShort(getContext(), "加载收藏单词出错: " + e.getMessage());
                    showEmptyState(true);
                    showAlphabetIndexView(false);
                });
            }
        }).start();
    }
    
    /**
     * 创建字母位置映射
     */
    private void createLetterPositionMap(List<Word> words) {
        letterPositionMap.clear();
        String lastFirstLetter = null;
        
        for (int i = 0; i < words.size(); i++) {
            String word = words.get(i).getWord().toUpperCase();
            if (word.isEmpty()) continue;
            
            // 获取单词首字母
            String firstLetter = String.valueOf(word.charAt(0));
            
            // 如果是数字或其他非字母字符，归类为"#"
            if (!firstLetter.matches("[A-Z]")) {
                firstLetter = "#";
            }
            
            // 如果是新的字母分组，记录位置
            if (!firstLetter.equals(lastFirstLetter)) {
                letterPositionMap.put(firstLetter, i);
                lastFirstLetter = firstLetter;
            }
        }
        
        // 根据实际出现的字母创建索引项
        if (!letterPositionMap.isEmpty()) {
            List<String> availableLetters = new ArrayList<>(letterPositionMap.keySet());
            availableLetters.sort(String::compareTo);
            
            // 如果字母索引项不为空，设置到字母索引视图
            if (!availableLetters.isEmpty()) {
                mainHandler.post(() -> {
                    String[] indexItems = availableLetters.toArray(new String[0]);
                    alphabetIndexView.setIndexItems(indexItems);
                });
            }
        }
    }
    
    /**
     * 处理单词点击事件
     */
    private void onWordItemClick(Word word) {
        Log.d(TAG, "onWordItemClick: 点击单词: " + word.getWord());
        
        // 跳转到单词详情页
        Intent intent = new Intent(getActivity(), WordDetailActivity.class);
        intent.putExtra("word", word.getWord());
        intent.putExtra("phonetic", word.getPhonetic());
        intent.putExtra("definition", word.getDefinition());
        intent.putExtra("translation", word.getTranslation());
        startActivity(intent);
    }
    
    /**
     * 处理收藏按钮点击事件
     */
    private void onFavoriteClick(Word word, boolean isFavorite) {
        Log.d(TAG, "onFavoriteClick: " + word.getWord() + ", isFavorite: " + isFavorite);
        
        // 通过FavoriteManager更新数据库
        boolean success = favoriteManager.toggleFavorite(word.getWord(), isFavorite);
        
        if (success) {
            // 如果是在收藏页面取消收藏，立即从列表中移除
            if (!isFavorite) {
                loadFavoriteWords();
            }
            
            // 提示用户
            String message = isFavorite ? 
                    getString(R.string.added_to_favorites, word.getWord()) : 
                    getString(R.string.removed_from_favorites, word.getWord());
            ToastManager.showShort(getContext(), message);
        } else {
            // 操作失败，显示具体的失败原因
            String message = isFavorite ? 
                    getString(R.string.favorite_add_failed, word.getWord()) : 
                    getString(R.string.favorite_remove_failed, word.getWord());
            ToastManager.showShort(getContext(), message);
        }
    }
    
    // 显示或隐藏空状态视图
    private void showEmptyState(boolean isEmpty) {
        if (isEmpty) {
            favoritesRecycler.setVisibility(View.GONE);
            emptyStateLayout.setVisibility(View.VISIBLE);
        } else {
            favoritesRecycler.setVisibility(View.VISIBLE);
            emptyStateLayout.setVisibility(View.GONE);
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 移除所有回调，防止内存泄漏
        letterHintHandler.removeCallbacks(hideLetterHintRunnable);
    }
} 